﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MetroFramework.Forms;
using System.Dynamic;
using Facebook;
using System.Xml;
using System.Xml.Xsl;
using System.IO;

namespace FBMarketing
{
    public partial class frmMain : MetroForm
    {
        private User currentUser;
        //

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            //WebBrowserHelper.ClearCache();
            //
            if (!Common.Authorized)
            {
                frmLogin frm = new frmLogin();
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    currentUser = frm.CurrentUser;
                    //
                    if (currentUser != null)
                    {
                        lblUsername.Text = currentUser.Name;
                        ptbAvatar.Load(currentUser.Avatar);
                    }
                }
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            //trước khi tìm kiếm thì lôi dữ liệu cũ ra
            ReadXml();
            if (String.IsNullOrEmpty(txtKeyword.Text))
                return;
            //
            var fb = new FacebookClient(Common.AccessToken);
            string sType = "group";
            string strQuery = "";
            dynamic results;
            switch (tabFilter.SelectedTab.Name.ToUpper())
            {
                case "TPGROUP":
                    sType = "group";
                    strQuery = "/search?q=" + txtKeyword.Text + "&type=" + sType;
                    break;
                case "TPFRIEND":
                    sType = "user";
                    strQuery = "me/friends";
                    break;
                case "TPEVENT":
                    sType = "event";
                    strQuery = "/search?q=" + txtKeyword.Text + "&type=" + sType;
                    break;
                case "TPPAGE":
                    sType = "page";
                    strQuery = "/search?q=" + txtKeyword.Text + "&type=" + sType;
                    break;
                case "TPLINK":
                    sType = "";
                    break;
                case "TPURL":
                    break;
            }
            results = fb.Get(strQuery);
            foreach (dynamic item in results.data)
            {
                dgvList.Rows.Add(dgvList.Rows.Count + 1, false, item.id, item.name, sType,"");
            }
            while (results.paging.next != null)
            {
                results = fb.Get(results.paging.next);
                foreach (dynamic item in results.data)
                {
                    dgvList.Rows.Add(dgvList.Rows.Count + 1, false, item.id, item.name, sType,"");
                }
            }
            //Sau khi tìm xong thì lưu vào xml
            WriteXml();
        }

        private void btnAddAccount_Click(object sender, EventArgs e)
        {
            frmLogin frm = new frmLogin();
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                currentUser = frm.CurrentUser;
                //
                if (currentUser != null)
                {
                    lblUsername.Text = currentUser.Name;

                    var fb = new FacebookClient(Common.AccessToken);
                    //dynamic pic = fb.Get("/me/picture?type=large");
                    //ptbAvatar.Load(pic.data.picture);
                }
            }
        }

        private void btnRemoveList_Click(object sender, EventArgs e)
        {
            dgvList.Rows.Clear();
        }

        private void dgvList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvList.Columns[e.ColumnIndex] == colId)
            {
                string sId = dgvList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                frmProfile frm = new frmProfile();
                frm.IdLink = sId;
                frm.ShowDialog();
            }
        }

        private void metroButton4_Click(object sender, EventArgs e)
        {
            var fb = new FacebookClient(Common.AccessToken);
            if (cbxFeed.Checked)
            {
                //var fb = new FacebookClient(Common.AccessToken);
                //foreach (DataGridViewRow row in dgvList.Rows)
                //{
                //    if (Convert.ToBoolean(row.Cells["colCheck"].Value))
                //    {
                        //string uid = row.Cells["colId"].Value.ToString();
                string uid = "100000317517455";
                        //
                        dynamic messagePost = new ExpandoObject(); 
                        messagePost.picture = "https://yaplex.com/media/default/logos/yaplex.png";
                        messagePost.link = "https://yaplex.com/"; 
                        messagePost.name = "[name] Fber8x"; 
                        messagePost.message = "[message] Xin chào";
                        messagePost.access_token = Common.AccessToken;
                        //string acccessToken = "xxxx5120330xxxx|4xxxxx0c0f95bd3f62dxxxxx.1-10000xx4x73xxxx|2xx5xxx0566xxxx|z2xxxx37dxxxxsdDS23s_Sah34a";
                        //
                        try
                        {
                            var postId = fb.Post(uid + "/feed", messagePost);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                //    }
                //}
            }

            if (cbxJoin.Checked)
            {
                ///GROUP_ID/members/USER_ID 
                foreach (DataGridViewRow row in dgvList.Rows)
                {
                    if (Convert.ToBoolean(row.Cells["colCheck"].Value))
                    {
                        string uid = row.Cells["colId"].Value.ToString();
                        //string uid = "1125444727472238";
                        
                        dynamic messagePost = new ExpandoObject();
                        messagePost.from = currentUser.Id;
                        //messagePost.member = "";//Người giới thiệu, add người # vào group
                        
                        try
                        {
                            var postId = fb.Post(uid + "/members", messagePost);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }
                }
            }
        }

        private DataTable GetDataTableFromDGV(DataGridView dgv, string tblName)
        {
            var dt = new DataTable(tblName);
            foreach (DataGridViewColumn column in dgv.Columns)
            {
                if (column.Visible)
                {
                    // You could potentially name the column based on the DGV column name (beware of dupes)
                    // or assign a type based on the data type of the data bound to this DGV column.
                    dt.Columns.Add();
                }
            }

            object[] cellValues = new object[dgv.Columns.Count];
            foreach (DataGridViewRow row in dgv.Rows)
            {
                for (int i = 0; i < row.Cells.Count; i++)
                {
                    cellValues[i] = row.Cells[i].Value;
                }
                dt.Rows.Add(cellValues);
            }

            return dt;
        }
        private void metroButton3_Click(object sender, EventArgs e)
        {
            
        }
        private void WriteXml()
        {
            string xmlString = string.Empty;
            DataTable dt = dt = GetDataTableFromDGV(dgvList, "Data");
            string FilePath = Application.StartupPath + @"\Data.xml";
            //Lưu vào xml
            if (dt != null)
            {
                if (!File.Exists(FilePath))
                {
                    var filestream = new FileStream(FilePath, FileMode.Create);
                    dt.WriteXml(filestream);
                }
                else
                    dt.WriteXml(FilePath);
            }
        }
        private void ReadXml()
        {
            DataTable dt = new DataTable();
            string FilePath = Application.StartupPath + "\\ Data.xml";
            if (File.Exists(FilePath))
            {
                FileStream fsReadXML = new FileStream(FilePath, FileMode.Open);

                dt.ReadXml(fsReadXML);
                dgvList.DataSource = dt;

            }
        }
    }
}
